package com.doge.calcalbum.business

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import android.webkit.*
import com.doge.calcalbum.core.BaseActivity
import com.doge.calcalbum.databinding.ActivityWebBinding
import com.doge.calcalbum.utils.*

class WebActivity : BaseActivity() {
    private val binding by lazy { ActivityWebBinding.inflate(layoutInflater) }
    private val title: String? by lazy { intent.getStringExtra(EXTRA_TITLE) }
    private val url by lazy { processUrl(intent.getStringExtra(EXTRA_URL)!!) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initialViews()
        binding.toolbar.binding.pageTitle.text = title
        binding.webView.loadUrl(url)
        binding.loadingProgress.start()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        binding.webView.reload()
    }

    private fun initialViews() {
        binding.toolbar.binding.pageBack.setOnClickCallback {
            finish()
        }
        val webSettings = binding.webView.settings
        webSettings.textZoom = 100
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.javaScriptEnabled = true
        webSettings.allowContentAccess = true
        webSettings.setAppCacheEnabled(false)
        webSettings.builtInZoomControls = false
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE //设置缓存 // 解决js好像调用不了的问题 具体问 陈恩典
        webSettings.mixedContentMode =
            WebSettings.MIXED_CONTENT_ALWAYS_ALLOW // https://blog.csdn.net/zlgzh/article/details/70171746 https页面加载http图片
        webSettings.domStorageEnabled = true
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        webSettings.blockNetworkImage = false
        webSettings.javaScriptCanOpenWindowsAutomatically = true//支持js调用window.open方法
        webSettings.setSupportMultipleWindows(true)// 设置允许开启多窗口
        binding.webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
        binding.webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                if (title.isNullOrEmpty()) {
                    binding.toolbar.binding.pageTitle.text = view?.title
                }
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                log("WebActivity shouldOverrideUrlLoading $url")
                return if (url.startsWith("http:") ||
                    url.startsWith("https:")) {
                    false
                } else {
                    try {
                        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                    } catch (e: Throwable) {
                        // android.content.ActivityNotFoundException: No Activity found to handle Intent
                    }
                    true
                }
            }
        }
        binding.webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress >= 100) {
                    binding.loadingProgress.stop()
                }
            }
        }
    }

    private fun processUrl(url: String): String {
        log("WebActivity url $url")
        return url
    }

    private fun canGoBack(): Boolean {
        return try {
            binding.webView.canGoBack()
        } catch (e: Throwable) {
            e.printStackTrace()
            false
        }
    }

    override fun onBackPressed() {
        if (canGoBack()) {
            binding.webView.goBack()
        } else {
            finish()
        }
    }

    companion object {
        private const val EXTRA_TITLE = "title"
        private const val EXTRA_URL = "url"

        fun start(context: Context?, url: String?, title: String? = null) {
            if (context == null || url == null) return
            context.startActivity(Intent(context, WebActivity::class.java).apply {
                if (context == appContext) flags = Intent.FLAG_ACTIVITY_NEW_TASK
                putExtra(EXTRA_URL, url)
                title?.let { putExtra(EXTRA_TITLE, it) }
            })
        }
    }
}
